package com.testshiro.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.web.BaseController;
import com.base.util.ObjMapUtil;
import com.base.util.PageUtil;
import com.base.criteria.Page;
import com.base.web.JModelAndView;
import com.base.model.ResultData;
import com.base.model.RetMsg;
import com.testshiro.entity.SysAccount;
import com.testshiro.entity.SysAutho;
import com.testshiro.service.SysAccountService;
import com.testshiro.tools.MD5;
import com.testshiro.utils.CommonValue;

/**
 * 
 * <br>
 * <b>功能：</b>SysAccountController<br>
 * <br>
 */
@Controller
@RequestMapping(value = "/data/sysaccount")
public class SysAccountController {

	private final static Logger log = Logger
			.getLogger(SysAccountController.class);
	@Resource
	private SysAccountService sysaccountService;

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg login(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		RetMsg retmsg = new RetMsg();
		List<SysAccount> ret = null;
		Map<String, Object> tmp = new HashMap<String, Object>();
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		Page page = new Page();
		page.clear();
		page.setCondition(tmp);

		ret = sysaccountService.login(loginName, MD5.MD5Encode(password));
		if (ret.size() < 1) {
			retmsg.setCode(-1);
			retmsg.setMsg("错误的用户名或密码！");
		} else {
			SysAccount account = ret.get(0);
			if (account.getIsDel() == 0) {
				SecurityUtils.getSecurityManager().logout(
						SecurityUtils.getSubject());
				HttpSession session = request.getSession();
				session.setAttribute("loginUser", account);
				UsernamePasswordToken token = new UsernamePasswordToken(
						account.getLoginName(), account.getPassword());
				Subject subject = SecurityUtils.getSubject();
				subject.login(token);
			} else {
				retmsg.setCode(-1);
				retmsg.setMsg("您的账户已经被禁用！请联系管理员！");
			}

		}
		return retmsg;
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	@ResponseBody
	public RetMsg logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RetMsg retmsg = new RetMsg();
		HttpSession session = request.getSession();
		session.setAttribute("loginUser", null);
		session.removeAttribute("loginUser");
		SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
		return retmsg;
	}

	@RequestMapping(value = "updatePwd", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg updatePwd(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		RetMsg retMsg = new RetMsg();
		retMsg.setCode(1);
		String oldPwd = request.getParameter("oldpassword");
		String newPwd = request.getParameter("newpassword");
		SysAccount acc = (SysAccount) request.getSession().getAttribute(
				"loginUser");
		/** 防空校验 **/
		if (oldPwd == null || oldPwd.trim().equals("")) {
			retMsg.setCode(0);
			retMsg.setMsg("旧密码不能为空！");
			return retMsg;
		}
		if (newPwd == null || newPwd.trim().equals("")) {
			retMsg.setCode(0);
			retMsg.setMsg("新密码不能为空！");
			return retMsg;
		}

		/** 校验旧密码 **/
		String pwd = MD5.MD5Encode(oldPwd);
		List<SysAccount> ret = sysaccountService.login(acc.getLoginName(), pwd);
		if (ret.size() < 1) {
			retMsg.setCode(0);
			retMsg.setMsg("旧密码错误！");
			return retMsg;
		}

		try {
			SysAccount updateObj = new SysAccount();
			updateObj.setSeqId(acc.getSeqId());
			updateObj.setPassword(MD5.MD5Encode(newPwd));
			sysaccountService.updateBySelective(updateObj);
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			retMsg.setCode(0);
			retMsg.setMsg("出错了！请联系管理员");
		}

		return retMsg;
	}

	/**
	 * 首页读取树结构
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "readMenuTree", method = RequestMethod.GET)
	public List<SysAutho> readMenuTree(HttpServletRequest request)
			throws Exception {
		List<SysAutho> ret = new ArrayList<SysAutho>();
		SysAccount user = (SysAccount) request.getSession().getAttribute(
				"loginUser");
		if (user == null) {
			return ret;
		}
		ret = sysaccountService.getMenuTree((long) user.getSeqId(),
				(long) CommonValue.parentIdDefault);

		return ret;
	}

	/**
	 * 读取叶子节点
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "readMenuLeaf", method = RequestMethod.GET)
	public List<SysAutho> readMenuLeaf(HttpServletRequest request, Long parentId)
			throws Exception {
		List<SysAutho> ret = new ArrayList<SysAutho>();
		SysAccount user = (SysAccount) request.getSession().getAttribute(
				"loginUser");
		if (user == null) {
			return ret;
		}
		ret = sysaccountService.getMenuTree((long) user.getSeqId(), parentId);
		return ret;
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public RetMsg create(SysAccount newObj) throws Exception {
		RetMsg retMsg = new RetMsg();

		try {
			sysaccountService.add(newObj);
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			retMsg.setCode(0);
			retMsg.setMsg("出错了！请联系管理员");
		}

		return retMsg;
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public RetMsg update(SysAccount updateObj) throws Exception {
		RetMsg retMsg = new RetMsg();

		try {
			sysaccountService.updateBySelective(updateObj);
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			retMsg.setCode(0);
			retMsg.setMsg("出错了！请联系管理员");
		}

		return retMsg;
	}

	@ResponseBody
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public RetMsg deleteByid(String id) throws Exception {
		RetMsg retMsg = new RetMsg();

		sysaccountService.delete(id);
		return retMsg;
	}

	@ResponseBody
	@RequestMapping(value = "readById", method = RequestMethod.GET)
	public SysAccount readById(Long seqId) throws Exception {
		SysAccount result = sysaccountService.queryById(seqId);
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "count", method = RequestMethod.GET)
	public Integer count(Integer page, Integer rows, SysAccount queryObj)
			throws Exception {
		Page pageObj = new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(rows);
		ObjMapUtil obj = new ObjMapUtil();
		Map tmp = obj.getValueMap(queryObj);
		pageObj.setCondition(tmp);
		Integer ret = sysaccountService.queryByCount(pageObj);
		return ret;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "readList", method = RequestMethod.GET)
	public List<SysAccount> readList(SysAccount queryObj) throws Exception {
		List<SysAccount> ret = null;
		ObjMapUtil obj = new ObjMapUtil();
		Map tmp = obj.getValueMap(queryObj);
		Page page = new Page();
		page.clear();
		page.setCondition(tmp);

		ret = sysaccountService.queryByList(page);
		return ret;
	}

	@ResponseBody
	@RequestMapping(value = "readAndCount", method = RequestMethod.GET)
	public ResultData readAndCount(Integer page, Integer rows,
			SysAccount queryObj) throws Exception {

		List<SysAccount> ret = null;
		Page pageObj = new Page();
		pageObj.setCurrentPage(page);
		pageObj.setPageSize(rows);
		ObjMapUtil obj = new ObjMapUtil();
		Map tmp = obj.getValueMap(queryObj);
		pageObj.setCondition(tmp);

		ret = sysaccountService.queryForPage(pageObj);

		ResultData<SysAccount> result = new ResultData<SysAccount>();
		result.setRows(ret);
		result.setTotal(pageObj.getTotalCount());
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "logicDel", method = RequestMethod.POST)
	public RetMsg logicDel(Integer id) throws Exception {
		RetMsg retMsg = new RetMsg();

		SysAccount queryObj = new SysAccount();
		queryObj.setSeqId(id);
		queryObj.setIsDel(1);
		try {
			sysaccountService.updateBySelective(queryObj);
		} catch (Exception e1) {
			e1.printStackTrace();
			log.info(e1.getMessage());
			retMsg.setCode(0);
			retMsg.setMsg("出错了！请联系管理员");
			return retMsg;
		}

		return retMsg;
	}

}
